<template>
  <el-dialog
    :visible.sync="isShow"
    width="1385px"
    @close="handleClose"
    :close-on-click-modal="false"
  >
    <div slot="title" class="dialogTitle">
      <div style="margin-right: 16px" v-if="!isEdit">
        {{ form.columnName }}
      </div>
      <el-input
        v-model="form.columnName"
        style="width: 170px;margin-right: 10px"
        v-if="isEdit"
        @blur="saveName"
        maxlength="10"
        minlength="1"
      >
      </el-input>
      <i class="el-icon-edit" @click="isEdit=true" v-if="type=='add'&&showStatu==0" style="color: #666666"></i>
    </div>
    <!--    选择课程-->
    <div v-show="showStatu==0" style="height: 700px;">
      <!--      检索-->
      <div class="searchBar">
        <el-form
          :model="model"
          ref="queryForm"
          size="small"
          :inline="true"
          label-width="68px"

        >
          <el-form-item  label="课程名称">
            <el-input
              style="width: 210px"
              v-model="model.courseName"
              placeholder="请输入课程名称"
              @keyup.enter.native="handleSearch"
              clearable
            />
          </el-form-item>
          <el-form-item label="分院名称" v-if="curRole!='branchAdmin'">
            <el-select
              style="width: 210px"
              filterable
              v-model="model.branchId"
              placeholder="请选择分院名称"
              clearable
            >
              <el-option
                v-for="item in branchList"
                :key="item.branchId"
                :label="item.branchName"
                :value="item.branchId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="主讲教师">
            <el-select
              style="width: 210px"
              filterable
              v-model="model.principalId"
              placeholder="请选择主讲教师"
              clearable
            >
              <el-option
                v-for="item in teacherList"
                :key="item.teacherId"
                :label="item.name"
                :value="item.teacherId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="课程类型">
            <el-select
              style="width: 210px"
              filterable
              v-model="model.courseType"
              placeholder="请选择课程类型"
              clearable
            >
              <el-option
                v-for="(item, index) of dict.type.course_type"
                :key="index"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学期">
            <el-select
              style="width: 210px"
              filterable
              v-model="model.semesterId"
              placeholder="请选择学期"
              clearable
            >
              <el-option label="全部" :value="''"></el-option>
              <el-option
                v-for="item in schoolSemesterList"
                :key="item.semesterId"
                :label="item.semesterName"
                :value="item.semesterId"
              >
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="模板类型">
            <el-select
              style="width: 210px"
              filterable
              v-model="model.courseTemplate"
              placeholder="请选择课程模版"
              clearable
            >
              <el-option label="全部" :value="''"></el-option>
              <el-option label="通用模版" :value="0"></el-option>
              <el-option label="工学一体模版" :value="1"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="排序">
            <el-select
              style="width: 210px"
              filterable
              v-model="model.sortSearch"
              placeholder="请选择排序"
            >
              <el-option
                v-for="item in sortList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button
              v-preventReClick
              type="primary"
              size="mini"
              @click="handleSearch"
            >搜索
            </el-button
            >
            <el-button
              v-preventReClick
              type="text"
              size="mini"
              @click="resetSearch"
              style="color:#666"
            >重置
            </el-button
            >
          </el-form-item>
        </el-form>
      </div>
      <!--      内容区域-->
      <div class="courseList">
        <div v-if="courseList.length>0" v-loading="loading">
          <div class="courseItems">
            <div v-for="(item, index) in courseList" :key="item.index" class="courseItem">
              <courseItem
                :item="item"
                :show-recommend="(!recommendIds.includes(item.courseId)||(item.type!=0&&item.type!=1))||(curRole=='schoolAdmin'&& item.type==1)"
                :isShowRecommendTag="recommendIds.includes(item.courseId)&&(item.type==0||item.type==1)"
                @recommend="handleRecommendCourse(item)"
              >
              </courseItem>
            </div>
          </div>
          <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="model.pageNum"
            :layout="'total, prev, pager, next, jumper'"
            :limit.sync="model.pageSize"
            @pagination="getCourseRecommendCourseList"
          />
        </div>
        <div v-if="courseList.length==0&&!loading">
          <el-empty description="暂无数据" class="emptyBox"></el-empty>
        </div>
      </div>
    </div>
    <!--    展示专栏-->
    <div v-show="showStatu==1" style="height: 700px;overflow: auto">
      <div class="tips">
        注：课程顺序可通过拖拽来调整排序
      </div>
      <div class="recommendCourseList">
        <div v-if="recommendCourseList.length>0">
            <draggable v-model="recommendCourseList" @end="onDragEnd" class="courseItems">
              <div v-for="(item, index) in recommendCourseList" :key="item.index" class="courseItem">
                <courseItem
                  :item="item"
                  :show-top="index!=0"
                  :show-bottom="index!=recommendCourseList.length-1"
                  :showRemove="curRole=='schoolAdmin'||(item.type==1&&branchId==item.branchId)"
                  :isShowRecommendTag="item.type==0||item.type==1"
                  @remove="handleRemoveCourse(item)"
                  @top="handleTopCourse(item)"
                  @bottom="handleBottomCourse(item)"
                >
                </courseItem>
              </div>
            </draggable>
        </div>
        <div v-else>
          <el-empty description="暂无展示" class="emptyBox" :image="require('@/assets/images/showColumn/emptyImg.png')"></el-empty>
        </div>
      </div>
    </div>
    <span slot="footer" class="dialog-footer">
    <el-button @click="handleClose" v-if="showStatu==0">取 消</el-button>
    <el-button type="primary" @click="nextStep" v-if="showStatu==0">下一步</el-button>
      <el-button type="primary" @click="prevStep" v-if="showStatu==1">上一步</el-button>
      <el-button @click="submitForm" v-if="showStatu==1">确定</el-button>
  </span>
  </el-dialog>
</template>
<script>
import { getSchoolSemesterList } from '@/api/schoolSemester/schoolSemester'
import { listPost_teacher } from '@/api/schoolOrganization/teacher'
import { listPost_branch } from '@/api/schoolOrganization/organization'
import { getCourseRecommendCourseList } from '@/api/home'
import courseItem from './courseItem.vue'
import { mapGetters } from 'vuex'
import draggable from 'vuedraggable';
import { courseRecommendList, saveColumnInfo } from '@/api/showColumn'
export default {
  name: 'ColumnDialog',
  dicts: ['course_type'],
  data() {
    return {
      isShow: false,
      type: 'add',
      showStatu: 0,
      isEdit: false,
      form: {
        columnName: '新增专栏'
      },
      //主讲教师列表
      teacherList: [],
      //分院列表
      branchList: [],
      schoolSemesterList: [],
      loading: true,
      total: 0,
      model: {
        sortSearch: 9,
        courseType: '',
        principalId: '',
        branchId: this.$store.getters.curRole == 'branchAdmin'? this.$store.getters.branchId : '',
        courseName: '',
        pageNum: 1,
        pageSize: 10,
        semesterId: '',
        courseTemplate: ''
      },
      sortList: [
        {
          value: 9,
          label: '综合排序'
        },
        {
          value: 0,
          label: '最新发布时间'
        },
        {
          value: 1,
          label: '累计考核次数(由高到低)'
        },
        {
          value: 2,
          label: '累计考核次数(由低到高)'
        },
        {
          value: 3,
          label: '累计结课人数(由高到低)'
        },
        {
          value: 4,
          label: '累计结课人数(由低到高)'
        },
        {
          value: 5,
          label: '当前在学人数(由高到低)'
        },
        {
          value: 6,
          label: '当前在学人数(由低到高)'
        },
        {
          value: 7,
          label: '课程总点击量(由高到低)'
        },
        {
          value: 8,
          label: '课程总点击量(由低到高)'
        }
      ],
      //课程列表
      courseList: [],
      // 推荐课程列表
      recommendCourseList: [],
      columnId:void 0,
      recommendIds:[]

    }
  },
  components: { courseItem,draggable},
  computed: {
    ...mapGetters(['curRole', 'branchId']),
  },
  watch: {
    'model.branchId': {
      handler(val) {
        this.getTeacher()
      },
      deep: true
    },
    'isShow': {
      async handler(val) {
        if (val) {
          await this.getSchoolSemester()
          this.getTeacher()
          this.getBranch()
          this.getCourseRecommendCourseList()
        }
      },
      immediate: true, // 立即生效
      deep: true
    }
  },
  methods: {
    show(id, columnName) {
      if (id) {
        this.type = 'edit'
        this.columnId = id
        this.form.columnName = columnName
        this.getColumnRecommendCourseList(id)
      } else {
        this.type = 'add'
      }
      this.isShow = true
    },
    handleSearch() {
      // 备注：产品要求搜索条件变动，页面回到第一页，
      this.model.pageNum = 1
      this.getCourseRecommendCourseList()
    },
    resetSearch() {
      this.model = {
        sortSearch: 9,
        semesterId: '',
        courseType: '',
        principalId: '',
        branchId: this.$store.getters.curRole == 'branchAdmin'? this.$store.getters.branchId : '',
        courseName: '',
        pageNum: 1,
        pageSize: 10,
        courseTemplate: ''
      }
      this.getCourseRecommendCourseList()
    },
    // 获取教师列表
    getTeacher() {
      listPost_teacher({
        pageNum: 1,
        pageSize: 9999,
        schoolId: this.$store.getters.schoolId,
        branchId: this.model.branchId
      }).then((response) => {
        this.teacherList = response.rows
      })
    },
    getBranch() {
      listPost_branch({
        pageNum: 1,
        pageSize: 9999,
        schoolId: this.$store.getters.schoolId
      }).then((response) => {
        this.branchList = response.rows
      })
    },
    async getSchoolSemester() {
      let res = await getSchoolSemesterList()
      const { code, rows } = res
      if (code == 200) {
        this.schoolSemesterList = rows
      }
    },
    async getCourseRecommendCourseList() {
      try {
        this.loading = true
        let res = await getCourseRecommendCourseList(this.model)
        const { code, rows, total } = res
        if (code === 200) {
          this.total = total
          this.courseList = this.handleCourseList(rows)
        }
      } catch (e) {
        console.error(e)
      } finally {
        this.loading = false
      }
    },
    // 获取专栏内推荐课程列表
    async getColumnRecommendCourseList(id) {
      try{
      let res=await courseRecommendList({columnId:id});
      if(res.code==200){
        this.recommendCourseList=res.rows
        this.recommendIds=res.rows.map(e=>e.courseId)
      }
      }catch (e){
        console.log(e)
      }
    },
    // 根据选中的列表，处理获取数据
    handleCourseList(list) {
      if(list && list.length>0&&this.recommendCourseList.length>0){
        this.recommendCourseList.forEach(e=>{
          list.forEach(item=>{
            if(e.courseId==item.courseId){
              item.type = e.type
            }
          })
        })
      }
      return list
    },
    handleRecommendCourse(item) {
      item.type = this.curRole == 'schoolAdmin' ? 0 : 1;
      let isCourseIdFound = false;
      if (this.recommendCourseList.length > 0) {
        for (let e of this.recommendCourseList) {
          if (e.courseId == item.courseId) {
            e.type = item.type;
            isCourseIdFound = true;
            break;
          }
        }
      }
      if (!isCourseIdFound) {
        this.recommendCourseList.push(item);
        this.recommendIds.push(item.courseId);
      }

    },
    handleRemoveCourse(item) {
      this.courseList.forEach(e => {
        if (e.courseId == item.courseId) {
          e.type = null
        }
      })
      this.recommendCourseList.splice(this.recommendCourseList.findIndex(i => i.courseId == item.courseId), 1)
      this.recommendIds.splice(this.recommendIds.findIndex(i => i == item.courseId), 1)
    },
    handleTopCourse(item) {
      // 找到要置顶的元素的索引
      const index = this.recommendCourseList.findIndex(e => e.courseId === item.courseId)
      const idIndex =this.recommendIds.findIndex(e => e === item.courseId)
      if (index !== -1) {
        // 从数组中移除该元素
        const [removedItem] = this.recommendCourseList.splice(index, 1)
        // 将该元素添加到数组的第一个位置
        this.recommendCourseList.unshift(removedItem)
      }
      if(idIndex!==-1){
        const [removedItem] = this.recommendIds.splice(idIndex, 1)
        this.recommendIds.unshift(removedItem)
      }
    },
    handleBottomCourse(item) {
      // 找到要置底的元素的索引
      const index = this.recommendCourseList.findIndex(e => e.courseId === item.courseId)
      const idIndex =this.recommendIds.findIndex(e => e === item.courseId)
      if (index !== -1) {
        // 从数组中移除该元素
        const [removedItem] = this.recommendCourseList.splice(index, 1)
        // 将该元素添加到数组的最后一个位置
        this.recommendCourseList.push(removedItem)
      }
      if(idIndex!==-1){
        const [removedItem] = this.recommendIds.splice(idIndex, 1)
        this.recommendIds.push(removedItem)
      }
    },
    onDragEnd(){
      console.log(this.recommendCourseList,'klklklklkkllkl0-0-0-0-0-0-0-')
    },
    saveName(){
      if(this.form.columnName.trim().length<1){
        this.$message.error('专栏名称不能为空')
        return
      }else{
        this.isEdit=false
      }
    },
    handleClose() {
      this.form = {
        columnName: '新增专栏'
      }
      this.showStatu=0
      this.recommendCourseList = []
      this.recommendIds=[]
      this.resetSearch()
      this.isShow = false
      // this.$message.info('已取消')
    },
   async submitForm() {
      if(this.form.columnName.trim().length<1){
        this.$message.error('专栏名称不能为空')
        return
      }
      if(this.recommendCourseList.length==0){
        this.$message.error('专栏不能为空')
        return
      }
      try{
        if(this.recommendCourseList.length>0){
          this.recommendCourseList.forEach((e,i)=>{
            e.sort=i+1
          })
        }
        let res=await saveColumnInfo({ ...this.form,id:this.type=='edit'?this.columnId:'',courseList:this.recommendCourseList});
        if(res.code==200){
          this.$message.success('编辑成功')
          this.handleClose()
          this.$emit('refresh')
        }
      }catch(e){
        console.log(e)
      }

    },
    nextStep() {
      this.showStatu = 1
    },
    prevStep() {
      this.showStatu = 0
    }
  }
}
</script>
<style scoped lang="scss">
::v-deep .el-dialog__footer{
  text-align: center;
}
::v-deep .el-dialog .el-dialog__header {
  border-bottom: none;
}

::v-deep .el-form-item {
  margin-bottom: 16px;
  margin-right: 32px;
}
::v-deep .el-form-item__label{
  font-family: PingFangSC, PingFang SC, sans-serif;
  font-weight: 400;
  font-size: 14px;
  color: #666666;
}

.dialogTitle {
  display: flex;
  align-items: center;
  font-family: PingFangSC, PingFang SC, sans-serif;
  font-weight: 500;
  font-size: 18px;
  color: #333333;
  line-height: 25px;
}

.searchBar {
  display: flex;
  align-items: center;
  padding: 24px 12px 8px 24px;
  box-sizing: border-box;
  background-color: #f5f5f5;
  margin-bottom: 20px;
  border-radius: 5px;
}

.courseList {
  width: 100%;

  .courseItems {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(228px, 1fr));
    grid-gap: 20px;
    justify-content: center;

    .courseItem {
      flex: 0 0 auto;
      //margin: 0 20px 24px 0;
    }

    .courseItem:last-child {
      margin-right: 0;
    }
  }

  .emptyBox {
    margin-top: 135px;
  }
}

.tips {
  margin-bottom: 20px;
  font-family: PingFangSC, PingFang SC, sans-serif;
  font-weight: 400;
  font-size: 16px;
  color: #F89A33;
  line-height: 22px;
  cursor: default;
}

.recommendCourseList {
  width: 100%;

  .courseItems {
    width: 100%;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(228px, 1fr));
    grid-gap: 20px;
    justify-content: center;

    .courseItem {
      flex: 0 0 auto;
      //margin: 0 20px 24px 0;
    }

    .courseItem:last-child {
      margin-right: 0;
    }
  }

  .emptyBox {
    margin-top: 165px;
  }
}

</style>
